import { nextTick } from 'vue'
import { getPathAddonConfig } from "@/utils/pages";


class Lang {

    // il8n 实例化
    private i18n: any
    // 本地加载语言包
    private loadLocales: Array<string> = []
    // 插件语言包
    private addonLocales: any = {'zh-Hans':{}, en:{}}

    constructor(i18n: any) {
        this.i18n = i18n;
    }

    /**
     * 设置语言
     * 
     * @param locale 语言
     */
    public setLang(locale: string) {
        if (this.i18n.mode === 'legacy') {
            this.i18n.global.locale = locale;
        } else {
            this.i18n.global.locale = locale;
        }
        uni.setLocale(locale);
    }

    /**
     * 加载插件语言包
     * @param key 插件标识
     * @param locale 语言 
     */
    public async importAddonLocale (key: string, locale: string) {
        const data = await import(`../addons/${key}/locale/${locale}.json`);
        if (data && data.default) {
            for (const k in data.default) {
                this.addonLocales[locale]['addon_' + key + '.' + k] = data.default[k];
            }
        }
        this.loadLocales.push(`${key}_${locale}`);
    }

    /**
     * 加载语言包
     * @param path 路由路径 
     * @param locale 语言
     * @returns 
     */
    public async loadAddonLocaleLang(path: string, locale: string) {
        try {
            // 判断插件路径
            if (path.indexOf('addons/') == 0) {
                let config = getPathAddonConfig(path);
                if(config) {
                    if (this.loadLocales.includes(`${config['addon']}_${locale}`)) {
                        this.setLang(locale);
                        return nextTick();
                    }

                    await this.importAddonLocale(config['addon'], locale);
                    // 异步方法内调用动态设置标题setNavigationBarTitle失效
                    this.i18n.global.mergeLocaleMessage(locale, this.addonLocales[locale]);
                }
            }

            this.setLang(locale);
            return nextTick();
        } catch (e) {
            this.setLang(locale);
            return nextTick();
        }
    }
}

export default Lang;
